﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using Chaos;

public class SimpleMeshEdt
{
    static private string rootDir;


    [MenuItem("Assets/SimpleMesh/目录一键挂上SimpleMesh")]
    static public void MenuItem_SetSimpleMeshAndCompute()
    {
        if (Selection.assetGUIDs.Length == 1)
        {
            rootDir = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);

            if (System.IO.Directory.Exists(rootDir))
            {
                SetSimpleMeshAndCompute();
            }
        }
    }


    [MenuItem("Assets/SimpleMesh/目录一键删除SimpleMesh")]
    static public void MenuItem_DelSimpleMesh()
    {
        if (Selection.assetGUIDs.Length == 1)
        {
            rootDir = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);

            if (System.IO.Directory.Exists(rootDir))
            {
                DelSimpleMesh();
            }
        }
    }

    [MenuItem("Assets/SimpleMesh/影子多选提取0.2")]
    static public void MenuItem_SetSngSimpleMesh()
    {
        MenuItem_SetSngSimpleMeshByPer(0.2f);
    }

    [MenuItem("Assets/SimpleMesh/影子多选提取0.25")]
    static public void MenuItem_SetSngSimpleMesh2()
    {
        MenuItem_SetSngSimpleMeshByPer(0.25f);
    }

    [MenuItem("Assets/SimpleMesh/影子多选提取0.3")]
    static public void MenuItem_SetSngSimpleMesh3()
    {
        MenuItem_SetSngSimpleMeshByPer(0.3f);
    }

    [MenuItem("Assets/SimpleMesh/影子多选提取0.4")]
    static public void MenuItem_SetSngSimpleMesh4()
    {
        MenuItem_SetSngSimpleMeshByPer(0.4f);
    }

    [MenuItem("Assets/SimpleMesh/影子多选提取0.5")]
    static public void MenuItem_SetSngSimpleMesh5()
    {
        MenuItem_SetSngSimpleMeshByPer(0.5f);
    }

    [MenuItem("Assets/SimpleMesh/影子多选提取0.6")]
    static public void MenuItem_SetSngSimpleMesh6()
    {
        MenuItem_SetSngSimpleMeshByPer(0.6f);
    }

    static public void MenuItem_SetSngSimpleMeshByPer(float per)
    {
        if (Selection.assetGUIDs.Length > 0)
        {
            int cnt = Selection.assetGUIDs.Length;
            for(int i = 0; i < cnt;i++)
            {
                string path = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]);

                if (!System.IO.Directory.Exists(path))
                {
                    SetSimpleMeshAndComputeByPath(path, per, true);
                   
                }
                else
                {
                    Debug.LogError("请选择模型预制!");
                }
            }

            AssetDatabase.SaveAssets(); 

            for (int i = 0; i < cnt; i++)
            {
                string path = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[i]);

                path = path.Replace("ClientRes/", "ClientResPickUp/");
                path = path.Replace("/Model/", "/ModelShadow/");

                //ResPickUpTool.SetShadowModelSngMat(path);
            }

            //ResPickUpTool.shadowMat = null;
        }
    }

    static public void SetSimpleMeshAndCompute()
    {
        string[] files = System.IO.Directory.GetFiles(rootDir, "*.prefab", System.IO.SearchOption.AllDirectories);


        int count = files.Length;

        for (int i = 0; i < count; i++)
        {
            var path = files[i];

            SetSimpleMeshAndComputeByPath(path);
        }

        AssetDatabase.SaveAssets();
        EditorUtility.ClearProgressBar();
    }

    static public void SetSimpleMeshAndComputeByPath(string path,float VertexAmount = 0.55f,bool clearMeshSimple = false)
    {
        if (path.EndsWith(".meta"))
            return;

        string newPath = path.Replace("\\","/");
        newPath = newPath.Replace("/ArtRes/", "/ArtResPickUp/");
        newPath = newPath.Replace("/ClientRes/", "/ClientResPickUp/");
        newPath = newPath.Replace("/Model/", "/ModelShadow/");

        string prefabName = System.IO.Path.GetFileNameWithoutExtension(path);
        GameObject orgPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);

        GameObject prefab = GameObject.Instantiate(orgPrefab);
        prefab.name = prefabName;
        string driPre = Path.GetDirectoryName(newPath);
        if (!Directory.Exists(driPre))
            Directory.CreateDirectory(driPre);
        if (File.Exists(newPath))
            AssetDatabase.DeleteAsset(newPath);
        PrefabUtility.SaveAsPrefabAsset(prefab, newPath);

        prefab = AssetDatabase.LoadAssetAtPath<GameObject>(newPath);

        bool isContinue = false;

        SkinnedMeshRenderer[] skinMs = prefab.GetComponentsInChildren<SkinnedMeshRenderer>();
        int snt = skinMs.Length;
        for (int s = 0; s < snt; s++)
        {
            if (skinMs[s].sharedMesh == null)
            {
                Debug.LogError("ShareMesh Have Missing = " + skinMs[s].name + ":" + path);
                isContinue = true;
            }
            else if (skinMs[s].rootBone == null)
            {
                Debug.LogError("RootBone is Missing = " + skinMs[s].name + ":" + path);
                isContinue = true;
            }
        }

        if (prefab == null || isContinue)
            return;

        if(VertexAmount == 1f)
        {

        }

        MeshSimplify meshSimplify = prefab.GetComponent<MeshSimplify>();
        if (meshSimplify == null)
            meshSimplify = prefab.AddComponent<MeshSimplify>();
        meshSimplify.VertexAmount = VertexAmount;

        meshSimplify.SimplifiedMesh = MeshSimplify.CreateNewEmptyMesh(meshSimplify);
        MeshSimplify[] meshSList = prefab.GetComponentsInChildren<MeshSimplify>();
        int cnt = meshSList.Length;
        for (int i = 0; i < cnt;i++)
        {
            meshSList[i].SimplifiedMesh = MeshSimplify.CreateNewEmptyMesh(meshSList[i]);
        }

        meshSimplify.ComputeMesh(meshSimplify.MeshSimplifyRoot == null, Progress);
        SimpleMeshUtil.DoSaveMeshAssets(meshSimplify, clearMeshSimple);

        GameObject.DestroyImmediate(GameObject.Find(prefabName));
    }

    static public void DelSimpleMesh()
    {
        string[] files = System.IO.Directory.GetFiles(rootDir, "*.prefab", System.IO.SearchOption.AllDirectories);


        int count = files.Length;

        for (int i = 0; i < count; i++)
        {
            var path = files[i];

            float per = (i + 1) * 1.0f / count * 1.0f;
            EditorUtility.DisplayProgressBar("正在删除SimpleMesh", (i + 1) + "/" + count, per);

            if (path.EndsWith(".meta"))
                continue;

            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            GameObject newPrefab = GameObject.Instantiate(prefab);
            newPrefab.name = prefab.name;

            MeshSimplify[] skinMs = newPrefab.GetComponentsInChildren<MeshSimplify>();
            int snt = skinMs.Length;
            for (int s = 0; s < snt; s++)
            {
                GameObject.DestroyImmediate(skinMs[s]);
            }

            Simplifier[] spes = newPrefab.GetComponentsInChildren<Simplifier>();
            snt = spes.Length;
            for (int s = 0; s < snt; s++)
            {
                GameObject.DestroyImmediate(spes[s]);
            }

            PrefabUtility.SaveAsPrefabAsset(newPrefab,path);
            GameObject.DestroyImmediate(newPrefab);
        }

        AssetDatabase.SaveAssets();
        EditorUtility.ClearProgressBar();
    }

    static void Progress(string strTitle, string strMessage, float fT)
    {
        int nPercent = Mathf.RoundToInt(fT * 100.0f);

        
    }
}
